// app.js
const util = require('./utils/util')
App({
  onLaunch() {
    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 无网络系统提示
    wx.onNetworkStatusChange((result) => {
      if (!result.isConnected) {
        wx.showToast({
          title: '网络断开请检查',
          icon: 'error'
        })
      }
    })
    
    this.checkForUpdate(); // 检查是否最新版本
    this.userTrajectory();
    this.overShare();
  },
  // 记录用户操作轨迹
  userTrajectory: function() {
    var that = this;
    wx.onAppRoute((res) => {
      // 获取加载的页面
      let pages = getCurrentPages(),
      view = pages[pages.length-1],
      data;
      data = view.data;
      data.timeStart = Date.now();
      if (!data.addonHide) {
        var oldOnHide = view.onHide;
        data.addonHide = true;
        view['onHide'] = function(view) {
          let timeEnd = Date.now();
          var stayTime = timeEnd - data.timeStart;
          var stayArray = new Object();
          stayArray.openId = wx.getStorageSync('userInfo').openid;
          stayArray.edate = timeEnd;
          stayArray.sdate = data.timeStart;
          stayArray.value = stayTime;
          stayArray.type = 'onHide';
          stayArray.pageUrl = res.path;
          that.sendTrajectory(stayArray);
        }
        // 调用原来的onHide方法
        oldOnHide.call(that, res)  
      }
      if (!data.addonLoad) {
        var oldOnLoad = view.onUnload;
        data.addonLoad = true;
        view['onUnload'] = function(view) {
          let timeEnd = Date.now();
          var stayTime = timeEnd - data.timeStart;
          var stayArray = new Object();
          stayArray.openId = wx.getStorageSync('userInfo').openid;
          stayArray.edate = timeEnd;
          stayArray.sdate = data.timeStart;
          stayArray.value = stayTime;
          stayArray.type = 'onUnload';
          stayArray.pageUrl = res.path;
          that.sendTrajectory(stayArray);
        }
        oldOnLoad.call(that, res)
      }
    })
  },

  sendTrajectory: function(stayArray) {
    wx.request({
      url: this.globalData.userIp + 'home/userTrajectory',
      data: stayArray,
      header: {
        'content-type': 'application/json'
      },
      method: 'POST',
      success: function(res) {
        // console.log(stayArray, 'stayArray');
      }
    })
  },

  checkForUpdate: function() {
    const updateManager = wx.getUpdateManager()
    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      console.log(res.hasUpdate)
    })
    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新版本提示',
        content: '确认重启应用~',
        success: function (res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })
    updateManager.onUpdateFailed(function () {
      // 新版本下载失败
      wx.showModal({
        title: '已经有新版本上线',
        content: '请移除当前小程序，重新搜索打开~'
      })
    })
  },
  // 重写全局分享方法
  overShare: function () {
    //间接实现全局设置分享内容
    wx.onAppRoute(function (res) {
        // console.log(res, 'res');
        //获取加载的页面
        let pages = getCurrentPages(),
            //获取当前页面的对象
            view = pages[pages.length - 1],
            data;
        if (view) {
            data = view.data;
            // 判断是否需要重写分享方法
            if (!data.isOverShare) {
                data.isOverShare = true;
                view.onShareAppMessage = function () {
                    //重写分享配置
                    return {
                        title: '集美云平台',
                        path: "/pages/index/index",   //分享页面地址
                        imageUrl: "https://sz.jimei123.com/upLoadImg/indexImg/home3.jpg"
                    };
                }
            }
        }
    })
  },

  // 判断字符串是否都为空格
  isNull: function(str) {
    var regu = "^[ ]+$";
    var re = new RegExp(regu);
    return re.test(str); 
  },
  globalData: {
    userInfo: null,
    workTaskTemplateId: ['xkdLonAAXUGPFkClkk2JB6gJmgJ8wxM2TR7oYHt6yvg'],  // 企业日报推送
    defaultAvatarUrl: 'https://img0.baidu.com/it/u=345359896,661384602&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
    defaultAvatarUrl2: 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
    userIp4: "http://192.168.1.132:443/",
    userIp2: "http://192.168.107.102:443/", // JIMEI.内网ip
    userIp3: "https://xcxht.ydsjys.com/", // 个人服务器
    userIp: "https://sz.jimei123.com/", // 集美服务器
    nowTime: util.getNowDate(new Date()),
    zhuzuo: "©集美新材-邀请版"
  }
})
